﻿defClass(happyfarm.util, "Job", null, function(Job, Job_prototype){
    Job_prototype.init = function(){
        this.request = new happyfarm.util.Request();
        this.appLoader = new happyfarm.util.AppLoader();
        this.tools = new happyfarm.util.Tools();
    };
    
    //获取实时目标信息
    Job_prototype.getOutput = function(target){
        var url = "";
        var postData = "ownerId=" + target.owner.uId + "&place=" + target.farmIndex;
        if (target.owner.uin != null) {
            url = "http://happyfarm.qzone.qq.com/api.php?";
        } else {
            url = "http://happyfarm.xiaoyou.qq.com/api.php?";
        }
        this.request.doPostCommon(postData, url, "farmlandstatus", "getOutput");
        this.onFarmRun(target.owner, target.farm, target.farmIndex, 0);
    };
    
    //获得好友列表
    Job_prototype.getUserList = function(onUser){
		
        var result, result_qzone, result_xiaoyou;
        var postData = "refresh=true&user=true";
        if (document.getElementById("host1").checked) {
			host = document.getElementById("host1").value;
            result_qzone = this.request.doPostRequest(postData, "cgi_farm_getFriendList?", "friend");
			if (navigator.userAgent.indexOf("MSIE") > 0) {
				document.getElementById("test").innerHTML = result_qzone.responseText;
				result_qzone = document.getElementById("test").innerHTML;
				result_qzone = result_qzone.replace(/�,/g,"\",");
				result_qzone = result_qzone.replace(/�\"/g,"\",\"");
				result_qzone = result_qzone.replace(/:\"\",/g,":\" \",");
				result_qzone = result_qzone.replace(/\"\"/g,"\"");
				result_qzone = eval('(' + result_qzone + ')') ;
			} else if (navigator.userAgent.indexOf("Firefox") > 0) {
				result_qzone = eval('(' + result_qzone.responseText + ')') ;
			}
            result = result_qzone;
        }
		if (document.getElementById("host2").checked) {
			host = document.getElementById("host2").value;
            result_xiaoyou = this.request.doPostRequest(postData, "cgi_farm_getFriendList?", "friend");
            result_xiaoyou = result_xiaoyou.responseText;
			result_xiaoyou = eval('(' + result_xiaoyou + ')') ;
            result = result_xiaoyou;
        }
        if (result == null || result.errorType == "validateCode") {
            return result;
        }
        
        if (document.getElementById("host1").checked && document.getElementById("host2").checked) {
			/*
			for(var i=0;i<result_qzone.length;i++){
				result_xiaoyou[result_xiaoyou.length + i] = result_qzone[i];
			}
			*/
			
            result = result_xiaoyou.concat(result_qzone);
        }
        
        //按照userId降序
        result.sort(function(a, b){
            return parseInt(a["userId"]) > parseInt(b["userId"]) ? -1 : 1
        });
        
        //增加登录人信息
        var userFlag = true;
        //当选择双开的时候，剔除重复好友
        var uId = "";
        for (var i = 0; i < result.length; i++) {
            if (result[i].uId == myId) {
                userFlag = false;
            }
            //当选择双开的时候，剔除重复好友
            if (result[i].uId == uId) {
                result.splice(i, 1);
                i = i - 1;
            } else {
                uId = result[i].uId;
            }
        }
        if (userFlag) {
            result.push({
                "uId": myId,
                "userName": "自己",
                "exp": onUser.user.exp,
                "money": onUser.user.money,
                "uin": onUser.user.uinLogin
            });
        }
        
        //排序判断
        if (document.getElementById("sort1").checked == true) {
            //按照经验降序
            result.sort(function(a, b){
                return parseInt(a["exp"]) > parseInt(b["exp"]) ? -1 : 1
            });
        } else if (document.getElementById("sort2").checked == true) {
            //按照金币降序
            result.sort(function(a, b){
                return parseInt(a["money"]) > parseInt(b["money"]) ? -1 : 1
            });
        }
		
        return result;
    };
    
    //获取农作物的信息
    Job_prototype.getCropsInfo = function(cId){
        var crops = null;
        for (var i = 0; i < cropsInfo.length; i++) {
            if (cropsInfo[i].cId == cId) {
                crops = cropsInfo[i];
                break;
            }
        }
        return crops;
    };
    
    //生成个人信息
    Job_prototype.getUserInfo = function(){
        try {
			var postData = "ownerId=0";
            //var result = this.request.doPostCommon(null, "http://happyfarm.qzone.qq.com/api.php?", "user", "run");
			var result = this.request.doPostRequest(postData, "cgi_farm_index?", "user", "run", 1);
            result = eval('(' + result.responseText + ')');
			//校验FarmKey失败, 重试
			while(result.direction && result.direction=="校验FarmKey失败"){
				result = this.getUserInfo();
			}
			myId = result.user.uId;
			uinLogin = result.user.uinLogin;
            return result;
        } catch (e) {
        
        }
    };
    
    //收获果实
    Job_prototype.getCrops = function(ownerId, farmlandIndex, mine, userIndexId, uinX){
        var postData = "ownerId=" + ownerId + "&place=" + farmlandIndex;
        var result;
        //判断是否是自己的地，0：不是	1：是
        try {
            if (mine == 0) {
                result = this.request.doPostRequest(postData, "cgi_farm_steal_v2?", "farmlandstatus", "scrounge", null, uinX);
            } else {
                result = this.request.doPostRequest(postData, "cgi_farm_plant?", "farmlandstatus", "harvest");
            }
            result = eval('(' + result.responseText + ')');
            if (userIndexId && result) {
                if (result.code == 1) {
                    //如果是自己的果实可获得经验
                    if (mine == 1) {
                        if (result.exp) {
                            userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
                        }
                    }
                    //获得实际收获果实数量
                    if (result.harvest) {
                        userArray[userIndexId]["farmlandStatus"][farmlandIndex]["cropCount"] = parseInt(result.harvest);
                    }
                }
				userArray[userIndexId]["farmlandStatus"][farmlandIndex]["direction"] = result.direction;
            }
			return result;
        } catch (e) {
            //
        }
    };
    
    //商店信息
    Job_prototype.getSeedInfo = function(){
        try {
            //var result = this.request.doPostCommon(null, "http://happyfarm.qzone.qq.com/api.php?", "repertory", "getSeedInfo");
			var result = this.request.doPostCommon(null, "http://farm.qzone.qq.com/cgi-bin/cgi_farm_getseedinfo?", "repertory", "getSeedInfo");
            result = eval('(' + result + ')');
			if(result.errorType){
				return result;
			}
            result.push({
                "cId": 46,
                "cName": "爱心果",
                "cType": 1,
                "growthCycle": 111600,
                "maturingTime": 3,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 64,
                "cName": "大葱",
                "cType": 1,
                "growthCycle": 39600,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 66,
                "cName": "鲜姜",
                "cType": 1,
                "growthCycle": 39600,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 71,
                "cName": "小白菜",
                "cType": 1,
                "growthCycle": 39600,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 73,
                "cName": "菠菜",
                "cType": 1,
                "growthCycle": 61200,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 69,
                "cName": "莴笋",
                "cType": 1,
                "growthCycle": 198000,
                "maturingTime": 4,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 120,
                "cName": "蒲公英",
                "cType": 1,
                "growthCycle": 57600,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 118,
                "cName": "水仙花",
                "cType": 1,
                "growthCycle": 111600,
                "maturingTime": 2,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 115,
                "cName": "兰花",
                "cType": 1,
                "growthCycle": 151200,
                "maturingTime": 4,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 62,
                "cName": "四叶草",
                "cType": 1,
                "growthCycle": 82800,
                "maturingTime": 2,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 81,
                "cName": "圣诞树",
                "cType": 1,
                "growthCycle": 46800,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 91,
                "cName": "山楂",
                "cType": 1,
                "growthCycle": 79200,
                "maturingTime": 1,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 82,
                "cName": "摇钱树",
                "cType": 1,
                "growthCycle": 133200,
                "maturingTime": 3,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 92,
                "cName": "稀世琉璃果",
                "cType": 1,
                "growthCycle": 165600,
                "maturingTime": 4,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
            result.push({
                "cId": 117,
                "cName": "康乃馨",
                "cType": 1,
                "growthCycle": 111600,
                "maturingTime": 5,
                "expect": 0,
                "output": 0,
                "sale": 0,
                "price": 0,
                "cLevel": 0,
                "cropExp": 0,
                "vip": null
            });
			
			//按照cId升序
            result.sort(function(a, b){
                return parseInt(a["cId"]) < parseInt(b["cId"]) ? -1 : 1
            });
			
            return result;
        } catch (e) {
        
        }
    };
    
    //背包信息
    Job_prototype.getUserSeed = function(){
        try {
            var result = this.request.doPostCommon(null, "http://farm.qzone.qq.com/cgi-bin/cgi_farm_getuserseed?", "repertory", "getUserSeed");
            result = eval('(' + result + ')');
            return result;
        } catch (e) {
        
        }
    };
	
	//生成用户农田图例
	Job_prototype.createUserFarm = function(i, farms, myFarm){
		var text = "";
		var farm = document.createElement("div");
		farm.className = "farm";
		
		var farmTitle = document.createElement("div");
		farmTitle.id = "farmTitle" + i;
		farmTitle.className = "farmTitle";
		if(farms.bitmap == "1"){
			text = document.createTextNode("第" + (i+1) + "块农田(红)");
		}else{
			text = document.createTextNode("第" + (i+1) + "块农田");
		}
		farmTitle.appendChild(text);
		farmTitle.onclick = function(){
			selectFarm = i;	
			for(var j=0;j<farmArray.length;j++){
				document.getElementById("farmTitle" + j).parentNode.className = "farm";
			}
			farmTitle.parentNode.className = "farmSelect";
		}
		
		var farmContent = document.createElement("div");
		farmContent.id = "farmContent" + i;
		
		//读取文件中的记录
		for(var j=0;j<farmRecords.length;j++){
			this.createFarmSeed(i, j, farmContent);
		}
		
		farm.appendChild(farmTitle);
		farm.appendChild(farmContent);
		myFarm.appendChild(farm);
    };
	
	//生成用户农田图例
	Job_prototype.createFarmSeed = function(i, j, farmContent){
		if(farmRecords[j].getAttribute("fId") == i){
			var farmSeed = document.createElement("div");
			farmSeed.id = farmRecords[j].getAttribute("cId");
			if(farmSeed.id>200 || farmSeed.id=="126"){
				farmSeed.className = "seedRed";
			}else{
				farmSeed.className = "seed";
			}
			farmSeed.style.width="100%";
			farmSeed.onclick = function(){
				farmSeed.parentNode.removeChild(farmSeed);
			}
			farmSeed.appendChild(document.createTextNode(farmRecords[j].getAttribute("cName")));
			farmContent.appendChild(farmSeed);
		}
	}
    
    //仓库信息
    Job_prototype.getUserCrop = function(){
        try {
            var result = this.request.doPostCommon(null, "http://nc.qzone.qq.com/cgi-bin/cgi_farm_getusercrop?f=1", null, null);
            result = eval('(' + result + ')');
            return result;
        } catch (e) {
        
        }
    };
    
    //清除杂草
    Job_prototype.clearWeeds = function(ownerId, farmlandIndex, userIndexId, uinX){
        postData = "ownerId=" + ownerId + "&place=" + farmlandIndex;
        try {
            var result = this.request.doPost(postData, "cgi_farm_opt?", "farmlandstatus", "clearWeed", null, uinX);
            result = eval('(' + result + ')');
            if (result) {
                if (result.code == 1) {
                    //经验满后，停止除草
                    if (document.getElementById("Auto-act").checked && parseInt(result.money) == 0 && parseInt(result.exp) == 0) {
                        document.getElementById("weeds").checked = false;
                    } else {
                        userArray[userIndexId]["farmlandStatus"][farmlandIndex]["weedsCount"] = parseInt(userArray[userIndexId]["farmlandStatus"][farmlandIndex]["weedsCount"]) + 1;
                        userArray[userIndexId]["goldCount"] = parseInt(userArray[userIndexId]["goldCount"]) + parseInt(result.money);
                        userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
                    }
                }
            }
        } catch (e) {
        
        }
    };
    
    //清除虫子
    Job_prototype.clearBorers = function(ownerId, farmlandIndex, userIndexId, uinX){
        postData = "ownerId=" + ownerId + "&place=" + farmlandIndex;
        try {
            var result = this.request.doPost(postData, "cgi_farm_opt?", "farmlandstatus", "spraying", null, uinX);
            result = eval('(' + result + ')');
            
            if (result) {
                if (result.code == 1) {
                    //经验满后，停止除虫
                    if (document.getElementById("Auto-act").checked && parseInt(result.money) == 0 && parseInt(result.exp) == 0) {
                        document.getElementById("borers").checked = false;
                    } else {
                        userArray[userIndexId]["farmlandStatus"][farmlandIndex]["borersCount"] = parseInt(userArray[userIndexId]["farmlandStatus"][farmlandIndex]["borersCount"]) + 1;
                        userArray[userIndexId]["goldCount"] = parseInt(userArray[userIndexId]["goldCount"]) + parseInt(result.money);
                        userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
                    }
                }
            }
        } catch (e) {
        
        }
    };
    
    //灌溉旱地
    Job_prototype.irrigation = function(ownerId, farmlandIndex, userIndexId, uinX){
        postData = "ownerId=" + ownerId + "&place=" + farmlandIndex;
        try {
            var result = this.request.doPost(postData, "cgi_farm_opt?", "farmlandstatus", "water", null, uinX);
            result = eval('(' + result + ')');
            
            if (result) {
                if (result.code == 1) {
                    //经验满后，停止灌溉
                    if (document.getElementById("Auto-act").checked && parseInt(result.money) == 0 && parseInt(result.exp) == 0) {
                        document.getElementById("dryland").checked = false;
                    } else {
                        userArray[userIndexId]["farmlandStatus"][farmlandIndex]["dryLand"] = true;
                        userArray[userIndexId]["goldCount"] = parseInt(userArray[userIndexId]["goldCount"]) + parseInt(result.money);
                        userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
                    }
                }
            }
        } catch (e) {
        
        }
    };
    
    
    //购买普通化肥
    Job_prototype.buyFertilizer = function(){
        postData = "number=1&tId=1&type=3";
        try {
            var result = this.request.doPost(postData, "cgi_farm_opt?", "usertool", "buyTool", null, null);
            result = eval('(' + result + ')');
            
            if (document.getElementById("Auto-saleAll").checked) {
                //金币不足时，变卖所有果实
                if (result.code == 0) {
                    this.saleAllCrops();
                    //再次购买普通化肥
                    result = this.request.doPost(postData, "cgi_farm_opt?", "usertool", "buyTool", null, null);
                }
            }
            
            if (result.code) {
                if (result.code == 1) {
                    fertilizerNum = fertilizerNum + 1;
                }
            }
        } catch (e) {
        
        }
    };
    
    //施普通化肥
    Job_prototype.fertilization = function(ownerId, farmlandIndex){
        postData = "ownerId=" + ownerId + "&place=" + farmlandIndex + "&tId=1";
        try {
            var result = this.request.doPost(postData, "cgi_farm_opt?", "farmlandstatus", "fertilize", null, uinX);
            result = eval('(' + result + ')');
            //当成功施肥后，减少一袋化肥
            if (result.code) {
                if (result.code == 1) {
                    fertilizerNum = fertilizerNum - 1;
                }
            }
        } catch (e) {
        
        }
    };
    
    //锄地
    Job_prototype.hoeing = function(ownerId, farmlandIndex, userIndexId, uinX){
        postData = "ownerId=" + ownerId + "&place=" + farmlandIndex;
        try {
            var result = this.request.doPost(postData, "cgi_farm_plant?", "farmlandstatus", "scarify", null, uinX);
            result = eval('(' + result + ')');
            if (result.exp && userIndexId) {
                userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
            }
            return result;
        } catch (e) {
        
        }
    };
    
    //购买种子
    Job_prototype.buySeeds = function(cId, num){
        if (!num) {
            num = 1;
        }
        var postData = "cId=" + cId + "&number=" + num;
        try {
            var result = this.request.doPostCommon(postData, "http://farm.qzone.qq.com/cgi-bin/cgi_farm_buyseed?", "repertory", "buySeed");
            result = eval('(' + result + ')');
            if (document.getElementById("Auto-saleAll").checked) {
                //金币不足时，变卖所有果实
                if (result.code != 1) {
                    this.saleAllCrops();
                    //再次购买种子
                    result = this.request.doPostCommon(postData, "http://farm.qzone.qq.com/cgi-bin/cgi_farm_buyseed?", "repertory", "buySeed");
                }
            }
        } catch (e) {
        
        }
    };
    
    //种地
    Job_prototype.farming = function(cId, ownerId, farmlandIndex, userIndexId, uinX){
        postData = "cId=" + cId + "&ownerId=" + ownerId + "&place=" + farmlandIndex;
        try {
            var result = this.request.doPost(postData, "cgi_farm_plant?", "farmlandstatus", "planting", null, uinX);
            result = eval('(' + result + ')');
            
            if (result.exp && userIndexId) {
                userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
            }
            return result;
        } catch (e) {
        
        }
    };
    
    //耕种
    Job_prototype.doFarming = function(owner, i, userIndexId, uinX){
        var userIndexId = owner.indexId;
        var defultCrop = null;
		var farmTitle = document.getElementById("farmTitle" + i).innerHTML;
		var farmContent = document.getElementById("farmContent" + i);
		if(farmTitle.indexOf("红")>0){
			defultCrop = document.getElementById("defult-red-crop").value;
		}else{
			defultCrop = document.getElementById("defult-crop").value;
		}
            
		var tmpCId = null;
        var cropsId = 0;
        var delflag = true;
			
        //准备先播种的种子
        if (document.getElementById("defult-crop-first").checked) {
            tmpCId = defultCrop;
        }else if (farmContent.childNodes.length > 0) {
			tmpCId = farmContent.firstChild.id;
		}else{
			tmpCId = defultCrop;
		}
            
		for (var j = 0; j < readyCrops.length; j++) {
            if (readyCrops[j][0] == tmpCId && readyCrops[j][2] == 1) {
                //如果是待购种子需要买种子，已购的不需要购买，直接种植
                cropsId = j;
                delflag = false;
                break;
            }
        }
        if (delflag) {
            this.buySeeds(tmpCId);
        }
            
        //种植农作物
        var result = this.farming(tmpCId, owner.uId, i, userIndexId, uinX);
        if (result) {
            if (result.code == 1) {
                //完成预先设定的种植作物后，在种子列表中删除这个种子
				if(cropsId != 0){
                   	this.appLoader.delReadyCrops(cropsId + 1);
				}
				if(farmContent.childNodes.length > 0 && tmpCId == farmContent.firstChild.id){
					farmContent.removeChild(farmContent.firstChild);
				}
            }
        }
    };
    
    //喂狗
    Job_prototype.feedDog = function(){
        try {
            var postData = "uId=" + myId;
            var result = this.request.doPostCommon(postData, "http://happyfarm.qzone.qq.com/api.php?", "dog", "feedDog");
            result = eval('(' + result + ')');
        } catch (e) {
        
        }
    };
    
    //变卖全部果实
    Job_prototype.saleAllCrops = function(cIds){
		var postData = "cIds=" + cIds + "&uId=" + myId;
        try {
            var result = this.request.doPost(postData, "cgi_farm_saleall?", "repertory", "saleAll", null, myId);
            result = eval('(' + result + ')');
            
            if (result.exp && userIndexId) {
                userArray[userIndexId]["expCount"] = parseInt(userArray[userIndexId]["expCount"]) + parseInt(result.exp);
            }
            return result;
        } catch (e) {
        
        }
    };
});
